'use client';

import { createContext, useContext, useEffect, ReactNode } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';

/**
 * 分析服务配置
 */
interface AnalyticsConfig {
  googleAnalyticsId?: string;
  baiduAnalyticsId?: string;
  hotjarId?: string;
  clarityId?: string;
  enablePerformanceTracking?: boolean;
  enableErrorTracking?: boolean;
  enableUserBehaviorTracking?: boolean;
}

/**
 * 分析上下文
 */
interface AnalyticsContextType {
  config: AnalyticsConfig;
  trackEvent: (eventName: string, parameters?: Record<string, unknown>) => void;
  trackPageView: (url: string, title?: string) => void;
  trackError: (error: Error, context?: Record<string, unknown>) => void;
  trackPerformance: (
    metric: string,
    value: number,
    context?: Record<string, unknown>
  ) => void;
  trackUserAction: (action: string, target?: string, value?: number) => void;
}

const AnalyticsContext = createContext<AnalyticsContextType | null>(null);

/**
 * 分析提供者组件
 */
interface AnalyticsProviderProps {
  children: ReactNode;
  config: AnalyticsConfig;
}

export function AnalyticsProvider({
  children,
  config,
}: AnalyticsProviderProps) {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  /**
   * 初始化Google Analytics
   */
  useEffect(() => {
    if (config.googleAnalyticsId && typeof window !== 'undefined') {
      // 加载gtag脚本
      const script1 = document.createElement('script');
      script1.async = true;
      script1.src = `https://www.googletagmanager.com/gtag/js?id=${config.googleAnalyticsId}`;
      document.head.appendChild(script1);

      // 初始化gtag
      const script2 = document.createElement('script');
      script2.innerHTML = `
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '${config.googleAnalyticsId}', {
          page_title: document.title,
          page_location: window.location.href,
          send_page_view: true
        });
      `;
      document.head.appendChild(script2);

      // 设置全局gtag函数
      (
        window as Window & {
          gtag?: (...args: unknown[]) => void;
          dataLayer?: unknown[];
        }
      ).gtag = function (...args: unknown[]) {
        const w = window as Window & { dataLayer?: unknown[] };
        w.dataLayer = w.dataLayer || [];
        w.dataLayer.push(args);
      };
    }
  }, [config.googleAnalyticsId]);

  /**
   * 初始化百度统计
   */
  useEffect(() => {
    if (config.baiduAnalyticsId && typeof window !== 'undefined') {
      const script = document.createElement('script');
      script.innerHTML = `
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?${config.baiduAnalyticsId}";
          var s = document.getElementsByTagName("script")[0]; 
          s.parentNode.insertBefore(hm, s);
        })();
      `;
      document.head.appendChild(script);
    }
  }, [config.baiduAnalyticsId]);

  /**
   * 初始化Hotjar
   */
  useEffect(() => {
    if (config.hotjarId && typeof window !== 'undefined') {
      const script = document.createElement('script');
      script.innerHTML = `
        (function(h,o,t,j,a,r){
          h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
          h._hjSettings={hjid:${config.hotjarId},hjsv:6};
          a=o.getElementsByTagName('head')[0];
          r=o.createElement('script');r.async=1;
          r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
          a.appendChild(r);
        })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
      `;
      document.head.appendChild(script);
    }
  }, [config.hotjarId]);

  /**
   * 初始化Microsoft Clarity
   */
  useEffect(() => {
    if (config.clarityId && typeof window !== 'undefined') {
      const script = document.createElement('script');
      script.innerHTML = `
        (function(c,l,a,r,i,t,y){
          c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
          t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
          y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
        })(window, document, "clarity", "script", "${config.clarityId}");
      `;
      document.head.appendChild(script);
    }
  }, [config.clarityId]);

  /**
   * 跟踪事件
   */
  const trackEvent = (
    eventName: string,
    parameters: Record<string, unknown> = {}
  ) => {
    if (typeof window === 'undefined') return;

    // Google Analytics
    if (config.googleAnalyticsId && 'gtag' in window) {
      const w = window as Window & { gtag?: (...args: unknown[]) => void };
      w.gtag?.('event', eventName, parameters);
    }

    // 百度统计
    if (config.baiduAnalyticsId && '_hmt' in window) {
      const w = window as Window & { _hmt?: unknown[] };
      w._hmt?.push([
        '_trackEvent',
        eventName,
        parameters.category || 'default',
        parameters.label || '',
      ]);
    }

    // Hotjar
    if (config.hotjarId && 'hj' in window) {
      const w = window as Window & { hj?: (...args: unknown[]) => void };
      w.hj?.('event', eventName);
    }

    // 自定义事件处理
    window.dispatchEvent(
      new CustomEvent('analytics-event', {
        detail: { eventName, parameters },
      })
    );
  };

  /**
   * 跟踪页面浏览
   */
  const trackPageView = (url: string, title?: string) => {
    if (typeof window === 'undefined') return;

    // Google Analytics
    if (config.googleAnalyticsId && 'gtag' in window) {
      const w = window as Window & { gtag?: (...args: unknown[]) => void };
      w.gtag?.('config', config.googleAnalyticsId, {
        page_title: title || document.title,
        page_location: window.location.origin + url,
        page_path: url,
      });
    }

    // 百度统计
    if (config.baiduAnalyticsId && '_hmt' in window) {
      const w = window as Window & { _hmt?: unknown[] };
      w._hmt?.push(['_trackPageview', url]);
    }
  };

  /**
   * 页面浏览跟踪
   */
  useEffect(() => {
    const url =
      pathname + (searchParams.toString() ? `?${searchParams.toString()}` : '');
    trackPageView(url, document.title);
  }, [pathname, searchParams, trackPageView]);

  /**
   * 跟踪错误
   */
  const trackError = (error: Error, context: Record<string, unknown> = {}) => {
    if (!config.enableErrorTracking) return;

    trackEvent('error', {
      error_message: error.message,
      error_stack: error.stack,
      error_name: error.name,
      ...context,
    });

    // 发送到错误监控服务
    if (typeof window !== 'undefined') {
      console.error('Analytics Error:', error, context);
    }
  };

  /**
   * 跟踪性能指标
   */
  const trackPerformance = (
    metric: string,
    value: number,
    context: Record<string, unknown> = {}
  ) => {
    if (!config.enablePerformanceTracking) return;

    trackEvent('performance_metric', {
      metric_name: metric,
      metric_value: value,
      ...context,
    });
  };

  /**
   * 跟踪用户行为
   */
  const trackUserAction = (action: string, target?: string, value?: number) => {
    if (!config.enableUserBehaviorTracking) return;

    trackEvent('user_action', {
      action,
      target,
      value,
    });
  };

  /**
   * 性能监控
   */
  useEffect(() => {
    if (!config.enablePerformanceTracking || typeof window === 'undefined')
      return;

    // 监控页面加载性能
    const observer = new PerformanceObserver(list => {
      list.getEntries().forEach(entry => {
        if (entry.entryType === 'navigation') {
          const navEntry = entry as PerformanceNavigationTiming;
          trackPerformance(
            'page_load_time',
            navEntry.loadEventEnd - navEntry.fetchStart
          );
          trackPerformance(
            'dom_content_loaded',
            navEntry.domContentLoadedEventEnd - navEntry.fetchStart
          );
          trackPerformance(
            'first_byte',
            navEntry.responseStart - navEntry.fetchStart
          );
        }

        if (entry.entryType === 'paint') {
          trackPerformance(entry.name.replace('-', '_'), entry.startTime);
        }

        if (entry.entryType === 'largest-contentful-paint') {
          trackPerformance('largest_contentful_paint', entry.startTime);
        }
      });
    });

    observer.observe({
      entryTypes: ['navigation', 'paint', 'largest-contentful-paint'],
    });

    return () => observer.disconnect();
  }, [config.enablePerformanceTracking]);

  /**
   * 错误监控
   */
  useEffect(() => {
    if (!config.enableErrorTracking || typeof window === 'undefined') return;

    const handleError = (event: ErrorEvent) => {
      trackError(new Error(event.message), {
        filename: event.filename,
        lineno: event.lineno,
        colno: event.colno,
      });
    };

    const handleUnhandledRejection = (event: PromiseRejectionEvent) => {
      trackError(new Error(String(event.reason)), {
        type: 'unhandled_promise_rejection',
      });
    };

    window.addEventListener('error', handleError);
    window.addEventListener('unhandledrejection', handleUnhandledRejection);

    return () => {
      window.removeEventListener('error', handleError);
      window.removeEventListener(
        'unhandledrejection',
        handleUnhandledRejection
      );
    };
  }, [config.enableErrorTracking]);

  const contextValue: AnalyticsContextType = {
    config,
    trackEvent,
    trackPageView,
    trackError,
    trackPerformance,
    trackUserAction,
  };

  return (
    <AnalyticsContext.Provider value={contextValue}>
      {children}
    </AnalyticsContext.Provider>
  );
}

/**
 * 使用分析服务的Hook
 */
export function useAnalytics() {
  const context = useContext(AnalyticsContext);
  if (!context) {
    throw new Error('useAnalytics must be used within an AnalyticsProvider');
  }
  return context;
}

/**
 * 分析事件Hook
 */
export function useTrackEvent() {
  const { trackEvent } = useAnalytics();
  return trackEvent;
}

/**
 * 页面浏览跟踪Hook
 */
export function useTrackPageView() {
  const { trackPageView } = useAnalytics();
  return trackPageView;
}

/**
 * 用户行为跟踪Hook
 */
export function useTrackUserAction() {
  const { trackUserAction } = useAnalytics();
  return trackUserAction;
}

/**
 * 性能跟踪Hook
 */
export function useTrackPerformance() {
  const { trackPerformance } = useAnalytics();
  return trackPerformance;
}

/**
 * 错误跟踪Hook
 */
export function useTrackError() {
  const { trackError } = useAnalytics();
  return trackError;
}

/**
 * 默认分析配置
 */
export const DEFAULT_ANALYTICS_CONFIG: AnalyticsConfig = {
  enablePerformanceTracking: true,
  enableErrorTracking: true,
  enableUserBehaviorTracking: true,
};
